/**
 * 订单簿类 - 管理特定资产的买卖订单
 */
class OrderBook {
  /**
   * 创建订单簿实例
   * @param {string} assetId - 资产ID
   */
  constructor(assetId) {
    this.assetId = assetId;
    this.buyOrders = [];  // 买单队列
    this.sellOrders = []; // 卖单队列
    this.trades = [];     // 成交记录
  }

  /**
   * 添加订单到订单簿
   * @param {Order} order - 订单对象
   */
  addOrder(order) {
    if (order.type === 'buy') {
      this.buyOrders.push(order);
      this.buyOrders.sort((a, b) => b.price - a.price); // 买单按价格降序排列
    } else if (order.type === 'sell') {
      this.sellOrders.push(order);
      this.sellOrders.sort((a, b) => a.price - b.price); // 卖单按价格升序排列
    }
    
    // 尝试匹配订单
    this.matchOrders();
  }

  /**
   * 匹配订单
   */
  matchOrders() {
    while (this.buyOrders.length > 0 && this.sellOrders.length > 0) {
      const bestBuy = this.buyOrders[0];
      const bestSell = this.sellOrders[0];
      
      // 检查是否可以成交 - 买单价格必须大于等于卖单价格
      if (bestBuy.price >= bestSell.price) {
        const tradePrice = (bestBuy.price + bestSell.price) / 2;
        // 成交数量为两者中的较小值
        const tradeQuantity = Math.min(bestBuy.quantity, bestSell.quantity);
        
        // 创建成交记录
        const trade = {
          assetId: this.assetId,
          price: tradePrice,
          quantity: tradeQuantity,
          buyOrderId: bestBuy.id,
          sellOrderId: bestSell.id,
          buyerId: bestBuy.investorId,
          sellerId: bestSell.investorId,
          timestamp: Date.now()
        };
        
        this.trades.push(trade);
        
        // 更新订单数量
        bestBuy.quantity -= tradeQuantity;
        bestSell.quantity -= tradeQuantity;
        
        // 移除已完成的订单
        if (bestBuy.quantity <= 0) {
          this.buyOrders.shift();
        }
        
        if (bestSell.quantity <= 0) {
          this.sellOrders.shift();
        }
      } else {
        // 没有可匹配的订单
        break;
      }
    }
  }

  /**
   * 导出订单簿数据
   * @returns {Object} 订单簿数据
   */
  exportOrderBook() {
    return {
      assetId: this.assetId,
      timestamp: new Date().toISOString(),
      buyOrders: this.buyOrders.map(order => ({
        id: order.id,
        investorId: order.investorId,
        price: order.price,
        quantity: order.quantity,
        type: order.type,
        timestamp: order.timestamp
      })),
      sellOrders: this.sellOrders.map(order => ({
        id: order.id,
        investorId: order.investorId,
        price: order.price,
        quantity: order.quantity,
        type: order.type,
        timestamp: order.timestamp
      })),
      trades: this.trades.map(trade => ({
        ...trade,
        timestamp: new Date(trade.timestamp).toISOString()
      }))
    };
  }

  /**
   * 获取订单簿快照
   * @returns {Object} 订单簿状态
   */
  getSnapshot() {
    return {
      assetId: this.assetId,
      buyOrders: [...this.buyOrders],
      sellOrders: [...this.sellOrders],
      trades: [...this.trades]
    };
  }

  /**
   * 获取最佳买价
   * @returns {number|null} 最佳买价
   */
  getBestBid() {
    return this.buyOrders.length > 0 ? this.buyOrders[0].price : null;
  }

  /**
   * 获取最佳卖价
   * @returns {number|null} 最佳卖价
   */
  getBestAsk() {
    return this.sellOrders.length > 0 ? this.sellOrders[0].price : null;
  }
}

module.exports = OrderBook;